package spUtil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
	
	protected static boolean isSeekingConnectionFirstTime = true;
	protected static int activeConnections;
	
	public static Connection getConnection() {
		Connection con = null;
		try {

			if (isSeekingConnectionFirstTime) {
				isSeekingConnectionFirstTime = false;
				try {
					Class.forName("com.mysql.jdbc.Driver");
				} catch (ClassNotFoundException ex) {
				}
			}
			String connectionUrl = "jdbc:mysql://" + RuntimeSettings.SERVER_IP
					+ ":" + RuntimeSettings.portNo + "/"
					+ RuntimeSettings.databaseName
					+ "?zeroDateTimeBehavior=convertToNull";
			con = DriverManager.getConnection(connectionUrl,
					RuntimeSettings.dbUserID, RuntimeSettings.dbPassword);
		} catch (SQLException ex) {
		}
		activeConnections++;
		return con;
	}	
	
	public static int update(Connection connection, String sql) throws SQLException {
		Statement statement = null;
		int rows = 0;
		try {
			statement = connection.createStatement();
			rows = statement.executeUpdate(sql);
			
		} catch (SQLException ex) {
		} finally {
			statement.close();
		}
		return rows;
	}
	
	
	public static int update(String sql) throws SQLException {

		int rowsUpdated = 0;
		Connection connection = null;
		try {
			connection = getConnection();
			connection.setAutoCommit(true);
			rowsUpdated = update(connection, sql);
		} catch (SQLException ex) {
		} finally {
			connection.close();
		}
		return rowsUpdated;
	}
	
	public static ResultSet readFromDB(String query, Connection connection) {
		ResultSet result = null;
		Statement stmt = null;
		try {
			if ((query.indexOf(" where ") >= 0)
					|| (query.indexOf("count ") >= 0)) {
				// ok
			} else {
			}
			stmt = connection.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			// System.out.println("in readFromDB inside result with query:\n" +
			// query);
			result = stmt.executeQuery(query);
		} catch (SQLException se) {
		}
		return result;
	}
	
	public static Connection getConnection(String dbName) {
		Connection conn;
		conn = getConnection();
		return conn;
	}

}
